/*
 * @Description:审批记录通知组件
 * @Author: anqing.liang
 * @Date: 2021-07-19 15:15:22
 * @LastEditTime: 2021-08-13 16:55:04
 * @LastEditors: anqing.liang
 */
import React, { Component, ReactNode } from 'react';
import { AxiosRequestConfig } from 'axios';
import {
    Modal,
    Button,
    Tag,
    Tooltip,
    notification,
    Spin,
} from 'hzero-ui';

import DisplayTable from './components/DisplayTable';
import { ApproveHistoryType, ApproveAction, ApproveDisplayType } from './utils/enum';
import { initAxiosConfig, queryData } from './utils/utils';
import styles from './ApproveHistory.less';
interface IProps {
    columns?: Array<object>;//table列控制//
    text: string;//按钮或链接文字
    modalProps?: object;//模态框覆盖属性
    modalChildren?: string | ReactNode;//模态框内容 默认为table
    tooltip?: string | ReactNode | boolean;//tooltip 默认不显示
    type?: string | ApproveHistoryType;//展示类型 超链接跳转/modal
    axiosConfig?: object | AxiosRequestConfig;//请求配置覆盖
    targetURL?: string;//展示类型为超链接时目标地址
    workflowKey: string | undefined;//工作流查询参数
    displayType?: string | ApproveDisplayType;//modal数据展示类型，默认展示最后一次流程
    //dispatch?: Dispatch<any>;
}
interface IState {
    axiosConfig: object | AxiosRequestConfig;
    visible: boolean;
    data: Array<Array<object>>;
    loading: boolean;
}
/**
 * 属性 说明 类型
 * @param columns          可选 table列控制 Array<object>
 * @param text             必选 按钮或链接文字  string
 * @param modalProps       可选 模态框覆盖属性  object;
 * @param modalChildren    可选 模态框内容 默认为table string | ReactNode;
 * @param tooltip          可选 tooltip 默认不显示 string | ReactNode | boolean;
 * @param type             可选 展示类型 超链接跳转/modal string | ApproveHistoryType;
 * @param axiosConfig      可选  请求配置覆盖 object | AxiosRequestConfig;
 * @param targetURL        可选 展示类型为超链接时目标地址 string;
 * @param workflowKey      必选 工作流查询参数 string | undefined;
 * @param displayType      可选 modal数据展示类型，默认展示最后一次流程  string | ApproveDisplayType
 */
export default class ApproveHistory extends Component<IProps, IState>{
    constructor(props) {
        super(props)
        this.state = {
            axiosConfig: initAxiosConfig({}),//请求配置
            visible: false,//modal显示状态
            data: [],//table数据源
            loading: false,
        }
    }
    //是否是URL跳转类型
    isUrl = this.props.type === ApproveHistoryType.Url;
    //是否显示tooltip
    isTooltip = this.props.tooltip ? true : false;
    //是否自定义modal内容
    isModalChildren = this.props.modalChildren ? true : false;
    //axiosConfig配置
    axiosConfig = this.props.axiosConfig || {};
    //是否展示链接或按钮
    isShow = Boolean(this.props.workflowKey);
    //modal属性配置
    modalProps = this.props.modalProps || {};
    //数据默认展示最后一流程
    displayType = this.props.displayType || ApproveDisplayType.Last;
    componentDidMount() {
        if (!this.isShow) {
            return
        }
        const { workflowKey } = this.props;
        if (!this.isUrl && this.axiosConfig) {
            this.setState({ axiosConfig: initAxiosConfig({ query: { workflowKey }, ...this.axiosConfig }) });
        }
    }
    async refreshData() {
        if (Boolean(this.state.axiosConfig)) {
            this.setState({ loading: true })
            const res = await queryData(this.state.axiosConfig);
            if (res) {
                this.setState({ data: res, loading: false });
            }
        }
    }
    handleGoto() {
        const { targetURL } = this.props;
        //console.log("targetURL", targetURL)
        if (!targetURL) {
            notification.error({ description: '', message: 'targetURL属性未配置' })
        }
        window.open(targetURL)
    }
    handleOpenModal(visible) {
        const axiosConfig = initAxiosConfig({ ...this.state.axiosConfig, ...this.axiosConfig })
        this.setState({ visible, axiosConfig })
        this.refreshData();
    }
    handleOk = () => {
        this.setState({
            visible: false,
        });
    }
    handleCancel = () => {
        this.setState({
            visible: false,
        });
    }
    handleMouseEnterTooltip() {
        const axiosConfig = initAxiosConfig({ ...this.state.axiosConfig, ...this.axiosConfig })
        this.setState({ axiosConfig })
        this.refreshData();
    }
    renderModalChildren() {
        if (this.isModalChildren) {
            const { modalChildren } = this.props;
            return modalChildren;
        } else {
            return this.renderTable(this.displayType as ApproveDisplayType);
        }
    }
    renderTable(type: ApproveDisplayType) {
        const { data, loading } = this.state
        if (type === ApproveDisplayType.Last) {
            //const _len = data[data.length - 1].length;
            const _lastRecord = data[data.length - 1];
            const lastRecord = [_lastRecord]
            return (
                <Spin spinning={loading}>
                    <DisplayTable
                        dataSource={lastRecord}
                        columns={this.columns}
                        style={{
                            background: 'white',
                            //width: '740px',
                        }}
                        tableProps={{ pagination: false }} />
                </Spin>
            )
        }
        return <DisplayTable dataSource={data} columns={this.columns} />
    }
    renderTooltipTitle = () => {
        const { tooltip } = this.props;
        if (typeof tooltip === 'boolean') {
            //默认显示最近一条审批记录
            return this.renderTable(ApproveDisplayType.Last)
        }
        return tooltip;
    }
    renderTooltip() {
        const {
            text,
            tooltip,
        } = this.props;
        if (this.isTooltip) {
            return (
                <Tooltip
                    overlayClassName={`${styles['approve-history-tooltip']}`}
                    overlayStyle={typeof tooltip === 'boolean' ? { margin: '0 0 0 0', maxWidth: '660px', } : {}}
                    placement="left"
                    title={() => this.renderTooltipTitle()} >
                    <a onMouseEnter={() => this.handleMouseEnterTooltip()}
                        onClick={() => this.handleOpenModal(true)}>{text}</a>
                </Tooltip>
            )
        } else {
            return (
                <Button
                    ghost
                    type='primary'
                    onClick={() => this.handleOpenModal(true)}
                >{text}</Button>
            )
        }
    }
    get columns(): Array<object> {
        if (Boolean(this.props.columns)) {
            return this.props.columns || [];
        } else {
            return [
                {
                    title: '审批动作',
                    dataIndex: 'action',
                    key: 'action',
                    width: 80,
                    render: (text) => {
                        return text ? (
                            <Tag color={ApproveAction.getStatusColor(text)}>{ApproveAction.getMeaning(text)}</Tag>
                        ) : null
                    }
                },
                {
                    title: '审批环节',
                    dataIndex: 'name',
                    key: 'name',
                    width: 120,
                },
                {
                    title: '审批人',
                    dataIndex: 'assigneeName',
                    key: 'assigneeName',
                    width: 120,
                    render: (text) => {
                        return text ? (
                            <Tooltip title={text}>{text}</Tooltip>
                        ) : null
                    }
                },
                {
                    title: '审批意见',
                    dataIndex: 'comment',
                    key: 'comment',
                    width: 120,
                    render: (text) => {
                        return text ? (
                            <Tooltip title={text}>{text}</Tooltip>
                        ) : null
                    }
                },
                {
                    title: '审批时间',
                    dataIndex: 'startTime',
                    key: 'startTime',
                    width: 150,
                },
            ]
        }
    }
    render() {
        const {
            text,
        } = this.props;
        return (
            <React.Fragment>
                {this.isShow && (this.isUrl
                    ? <a onClick={() => this.handleGoto()}>{text}</a>
                    : this.renderTooltip()
                )}
                <Modal
                    title='审批记录'
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    movable={true}
                    onCancel={this.handleCancel}
                    width='740px'
                    {...this.modalProps}
                >
                    {this.renderModalChildren()}
                </Modal>
            </React.Fragment>
        )
    }
}